package com.swak.persistence.mybatis.methods.impls;

import com.swak.define.ColumnDefine;
import com.swak.persistence.mybatis.methods.AbstractMethod;
import com.swak.persistence.mybatis.methods.Sqls;
import com.swak.utils.StringUtils;

/**
 * 删除语句
 * 
 * @author lifeng
 * @date 2021年1月21日 下午5:31:56
 */
public class Update extends AbstractMethod {

	@Override
	protected void doInject() {
		if (!this.supportMethod(Sqls.UPDATE)) {
			return;
		}

		String sql = new StringBuilder().append(UPDATE).append(SPACE).append(this.table.getName()).append(SPACE)
				.append(SET).append(SPACE).append(this.parseUpdateProperty()).append(SPACE).append(WHERE).append(SPACE)
				.append(this.parsePkEqualColumns()).append(SPACE).append(this.parseOptimismLockCheckColumn())
				.toString();

		this.addUpdateMappedStatement(this.table.entity, Sqls.UPDATE.getMethod(), sql);
	}

	protected String parseOptimismLockCheckColumn() {
		if (this.table.define.useOptimismLock()) {
			return OP_LOCK_CHECK;
		}
		return StringUtils.EMPTY;
	}

	/**
	 * 解析更新列
	 */
	protected String parseUpdateProperty() {
		StringBuilder sql = new StringBuilder();
		for (ColumnDefine column : this.table.columns) {
			if (!column.isPk() && !column.isCreateDate() && !column.isVersion()) {
				String name = column.name;
				String property = column.javaProperty;
				sql.append(name).append(EQUALS).append(HASH_LEFT_BRACE).append(property).append(RIGHT_BRACE)
						.append(SPLIT);
			}
		}

		if (this.table.define.useOptimismLock()) {
			sql.append(OP_LOCK_ADD);
		} else if (this.table.hasColumn()) {
			sql.delete(sql.lastIndexOf(SPLIT), sql.length() - 1);
		}
		return sql.toString();
	}
}
